<?php
namespace app\common\controller;
use think\Loader;
use think\Controller;
use think\Db;

/**
 * 后台公用基础控制器
 * @author taigu
 * @version 2017-9-22
 */
class IdexBaseController extends Controller {
    
    protected function _initialize() {
        parent::_initialize();
        if(!session("104")){
        	session("104",1);
			session("openid",null);
			session("info_user",null);
        }
		
		
        $cut_action = request()->action();
        $openid=session("openid");
		
        $acts=array('regist','order_page','hongb03','upload1','login','reg');
        if($cut_action == 'cz_pay_code' || $cut_action == 'about' || $cut_action == 'login' || $cut_action == 'contact'){
            $this->assign('action',request()->action());
        }else if($cut_action == 'glj' || $cut_action == 'friends' || $cut_action == 'share_erweim'){
        	 if(!$openid) {
            $this->redirect('index/index/regist?fx_id='.input('fx_id'));
			 }
        }else if(in_array($cut_action, $acts)){
        }else{
        	$this->exist_user();
        }
        $this->assign('action',request()->action());
		$this->assign('controller',request()->controller());
		
		//新用户领取奖励
		if(session('info_user')['is_receive']==0){
            $agency_id1=session('info_user')['agency_id1'];
            $where['id']=$agency_id1;
            $where['user_level']=2;
			//判断oem的鼓励金是否足够
            $s_score = db('info_oem')->where($where)->field('s_score')->find();
            $score = db('info_oem')->where('id',1)->field('score')->find();   
			// session('info_oem.s_score',$s_score['s_score']);
			if($score['score'] < $s_score['s_score']){
				session('info_user.is_receive',2);
			}
			
			$type=get_brower_type();//判断是微信还是支付宝打开
			if($type==2){//微信
				session('type_wxpay',2);
			}else{
				session('type_wxpay',1);
			}
		}
    }
    
	function atten(){
		$user_info=session("info_user");
		if($user_info['is_atten']!=1){
			$acts=array('index','pay_success','change_success');
			$cut_action = request()->action();
			$openid=session("openid");
			if(in_array($cut_action, $acts)){
				$access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".config('wxpay_appid')."&secret=".config("wxpay_appsercet");
			    $access_msg = json_decode(file_get_contents($access_token));
			    $token = $access_msg->access_token;
			    $subscribe_msg = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$token&openid=$openid&lang=zh_CN";
				$res=file_get_contents($subscribe_msg);
				file_put_contents("log.txt", $res."----".now_time().PHP_EOL, FILE_APPEND);
			    $jsondecode1 = json_decode($res); //对JSON格式的字符串进行编码
				$array1 = get_object_vars($jsondecode1);//转换成数组
				if(isset($array1['subscribe'])&&($array1['subscribe']==1)){
                    $user_id=db('info_user')->where("openid", $openid)->update(["is_atten"=>1]);
                    if($user_info['member_level']=="ratio_one" || empty($user_info['member_level'])){
                    $user_ratio=db('info_user')->where("openid", $openid)->update(["member_level"=>"ratio_two"]);
                    $user_info['member_level']="ratio_two";
                    }
                    $user_info['is_atten']=1;
					session("info_user",$user_info);
				}
			}
			
		}
		
	}
    	//判断会员是否存在并自动注册
	public function exist_user(){
		$user=session('info_user');
		$type=get_brower_type();//判断是微信还是支付宝打开
        $redirect='https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        //判断缓存是否被清除
        if(!$user) {
            //1支付宝打开,2微信打开，3账号登录
            if($type==1){
                $auth_code=input("auth_code");
                $url ='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='.config('alipay_appid').'&scope=auth_base&redirect_uri='.urlencode($redirect);
            }elseif($type==2){
                $auth_code=input("code");
                $url ='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wxpay_appid').'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_userinfo&state=STATE%23wechat_redirect&connect_redirect=1#wechat_redirect';
            }else{
                $this->redirect('index/index/login');
            }
            if(!$auth_code){
                Header("Location: $url");
                exit;
            }else{
                if($type==1){//支付宝openid
                    $pay_type = 3;
                    $field="alipay_id";
                    $openid=user_ali_id($auth_code);
                }elseif($type==2){//微信openid
                   	$pay_type = 2;
					$field="openid";
					$data=user_wx_id1($auth_code);
					$openid=$data['openid'];
					session('wx_user',$data);
                }
				session("openid",$openid);
            }
            $user_info = db('info_user')->where($field,$openid)->find();
            //判断该用户是否已存在
            if($user_info){
            	if(!$user_info['logo']&&$type==2&&isset($data)){
            		$res=db("info_user")->where('id',$user_info['id'])->update($data);
					if($res){
						$user_info = db('info_user')->where('id',$user_info['id'])->find();
					}
            	}
                session('info_user', $user_info);
                $this->redirect($redirect);
            }else{
                    //通过关注公众号生成的会员
                    $tj_user_info = db('info_user')->where('id',input('fx_id'))->find();
                    if(!$tj_user_info){
                        //通过他人分享、推荐关注
                        $ip=get_client_ip();  //get_client_ip()为tp自带函数，如没有，自己百度搜索。此处就不重复复制了
                        // $info = file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip='.$ip);  //新浪
                        // $url = 'http://ip.taobao.com/service/getIpInfo.php?ip='.$ip;                                          //淘宝
                        //判断关系：优先级市级代理、省级代理、直营市代理、最后才是平台。
                        $info = file_get_contents("http://api.map.baidu.com/location/ip?ak=2TGbi6zzFm5rjYKqPPomh9GBwcgLW5sS&ip={$ip}&coor=bd09ll");  //百度
                        $IPinfo = json_decode($info);

                        $address=$IPinfo->content->address_detail;      
                        $province =$address->province;                    //省
                        $city = $address->city;                           //市

                        //平台
                        $tj_user_info = db('info_user')->where('id',3)->find();
                        $info_oem = "";
                        //是否存在自营
                        $where1['oem_level']=2;
                        $where1['user_level']=2;
                        $where1['city'] = ['like','%'.$city.'%'];
                        $info_oem1 = db('info_oem')->where($where1)->select();
                       
                        if($info_oem1 && !empty($info_oem1[0]['ome_agent_id'])){
                            $info_oem=$info_oem1;
                        }

                        //是否存在省级代理
                        $where2['oem_level']=1;
                        $where2['user_level']=4;
                        $where2['province'] = ['like','%'.$province.'%'];
                        $info_oem2 = db('info_oem')->where($where2)->select();
                        if($info_oem2 && !empty($info_oem2[0]['ome_agent_id'])){
                            $info_oem=$info_oem2;
                        }

                        //是否存在市级代理
                        $where3['oem_level']=1;
                        $where3['user_level']=2;
                        $where3['city'] = ['like','%'.$city.'%'];
                        $info_oem3 = db('info_oem')->where($where3)->select();
                        if($info_oem3 && !empty($info_oem3[0]['ome_agent_id'])){
                            $info_oem=$info_oem3;
                        }

                        //查询代理默认商家关联用户的层级
                        if(!empty($info_oem)){
                            $agent= db('info_agent')->where('id',$info_oem[0]['ome_agent_id'])->find();
                            if($agent){
                                $agent_user_id=$agent['user_id'];
                                $tj_user_info = db('info_user')->where('id',$agent_user_id)->find();
                            }
                        }

                    }   
                    $data['level']			= $tj_user_info['id'];
                    $data['oem_id']			= $tj_user_info['oem_id'];
                    $data['agency_id1']		= $tj_user_info['agency_id1'];
                    $data['agency_id2']		= $tj_user_info['agency_id2'];
                    $data['salesman_id']	= $tj_user_info['salesman_id'];
                    $data['tj_pt']			= $tj_user_info['tj_pt'];
                    $data['tj_pt1']			= $tj_user_info['tj_pt1'];
                    $data['tj_agent']		= $tj_user_info['tj_agent']; 
                    $data[$field]			= $openid;
                    $data['add_time']		= now_time();
                    $data['reg_type']		= 1;  //公众号进入
                    $data['member_level']	= "ratio_two";
                    $user_id=Db::name('info_user')->insertGetId($data);
                    $cut_user_info = db('info_user')->where('id',$user_id)->find();
                    //获取用户信息
                    session('info_user', $cut_user_info);
                    if($type==2){
						receive();
					}
                    $this->redirect($redirect);
            }
       	}else{
            //关注
         	$this->atten();
       	}
	}
    //图片上传
    public function upload(){
        include_once ('././vendor/aliyun-oss-php-sdk/autoload.php');
        $files = $_POST["value"];
        $tmp = base64_decode($files);
        $fn = time()."_".rand(100000, 999999) . ".jpg";
        $fp = '././public/uploads/image/'. $fn;
        $fp1 = '././public/uploads/image/'. $fn;
        $res=file_put_contents( $fp, $tmp);
        $ossClient = new \OSS\OssClient('LTAIaqGtJ3JDXJvv', 'Q2kTcyepAHX0VOR44OtszVoyOKE8gl', 'oss-cn-shanghai.aliyuncs.com');
        try{
            $res=$ossClient->uploadFile("long3",$fn,$fp1);
            $src='https://long3.oss-cn-shanghai.aliyuncs.com/'.$fn;
            unlink($fp1);
            return json(["code"=>200,'url'=>$src]);
        } catch(OssException $e) {
            return json(["code"=>404,'msg'=>'上传错误']);
        }
    }
    
    public function wang_upload(){
        include_once ('././vendor/aliyun-oss-php-sdk/autoload.php');
        foreach ($_FILES as $name => $file) {
            $info = getimagesize($file['tmp_name']);
            $ext = image_type_to_extension($info['2']);
            $ossClient = new \OSS\OssClient('LTAIaqGtJ3JDXJvv', 'Q2kTcyepAHX0VOR44OtszVoyOKE8gl', 'oss-cn-shanghai.aliyuncs.com');
            $name=time()."_".rand(100000, 999999).$ext;
            try{
                $res=$ossClient->uploadFile("long3",$name,$file['tmp_name']);
                $result['code'] = 1;
                $result['msg'] = '上传成功！';
                $result['src']='http://long3.oss-cn-shanghai.aliyuncs.com/'.$name;
            } catch(OssException $e) {
                $result['code'] = 0;
                $result['msg'] = $file -> $e->getMessage();
            }
        }
        return json($result);
    }
    
}
